package com.cloudbroker.bcs.common.emoji;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by xuyn15828 on 2016/4/26.
 */
public class EmojiManager {
    private static final String PATH = "emojis.json";
    private static final Map<String, Emoji> EMOJIS_BY_ALIAS = new HashMap();
    private static final Map<String, Set<Emoji>> EMOJIS_BY_TAG = new HashMap();
    private static final List<Emoji> ALL_EMOJIS;
    private static final EmojiTrie EMOJI_TRIE;

    private EmojiManager() {
    }

    public static Set<Emoji> getForTag(String tag) {
        return tag == null?null:(Set)EMOJIS_BY_TAG.get(tag);
    }

    public static Emoji getForAlias(String alias) {
        return alias == null?null:(Emoji)EMOJIS_BY_ALIAS.get(trimAlias(alias));
    }

    private static String trimAlias(String alias) {
        String result = alias;
        if(alias.startsWith(":")) {
            result = alias.substring(1, alias.length());
        }

        if(result.endsWith(":")) {
            result = result.substring(0, result.length() - 1);
        }

        return result;
    }

    public static Emoji getByUnicode(String unicode) {
        return unicode == null?null:EMOJI_TRIE.getEmoji(unicode);
    }

    public static Collection<Emoji> getAll() {
        return ALL_EMOJIS;
    }

    public static boolean isEmoji(String string) {
        return string != null && EMOJI_TRIE.isEmoji(string.toCharArray()).exactMatch();
    }

    public static EmojiTrie.Matches isEmoji(char[] sequence) {
        return EMOJI_TRIE.isEmoji(sequence);
    }

    public static Collection<String> getAllTags() {
        return EMOJIS_BY_TAG.keySet();
    }

    static {
        try {
            InputStream e = EmojiLoader.class.getClassLoader().getResourceAsStream(PATH);
            //.getResourceAsStream(PATH);
            List emojis = EmojiLoader.loadEmojis(e);
            ALL_EMOJIS = emojis;
            Iterator var2 = emojis.iterator();

            while(var2.hasNext()) {
                Emoji emoji = (Emoji)var2.next();

                Iterator var4;
                String alias;
                for(var4 = emoji.getTags().iterator(); var4.hasNext(); ((Set)EMOJIS_BY_TAG.get(alias)).add(emoji)) {
                    alias = (String)var4.next();
                    if(EMOJIS_BY_TAG.get(alias) == null) {
                        EMOJIS_BY_TAG.put(alias, new HashSet());
                    }
                }

                var4 = emoji.getAliases().iterator();

                while(var4.hasNext()) {
                    alias = (String)var4.next();
                    EMOJIS_BY_ALIAS.put(alias, emoji);
                }
            }

            EMOJI_TRIE = new EmojiTrie(emojis);
            e.close();
        } catch (IOException var6) {
            throw new RuntimeException(var6);
        }
    }
}
